package loja.model.conta;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import loja.model.conta.operacao.Operacao;
import loja.model.conta.titular.Titular;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "conta_abstrata")
public abstract class ContaAbstrata {

	@Id
	@GeneratedValue
	private Long idConta;
	@OneToOne(cascade = CascadeType.ALL, optional = false)
	private Titular titular;
	@OneToMany(cascade = CascadeType.ALL)
	private List<Operacao> operacoes = new ArrayList<>();

	public ContaAbstrata() {
	}

	public Long getIdConta() {
		return idConta;
	}

	public void setTitular(Titular titular) {
		this.titular = titular;
	}

	public Titular getTitular() {
		return titular;
	}

	public void clearOperacoes() {
		this.operacoes.clear();

	}

	public void addOperacao(Operacao operacao) {
		this.operacoes.add(operacao);
	}

	public List<Operacao> listarOperacoes() {
		List<Operacao> operacoesClone = new ArrayList<>();
		for (Operacao operacao : operacoes) {
			operacoesClone.add((Operacao) operacao.clone());
		}
		return operacoesClone;
	}

	public BigDecimal getSaldoConta() {
		BigDecimal saldo = BigDecimal.ZERO;
		for (Operacao operacao : operacoes) {
			saldo = saldo.add(operacao.getValor());
		}
		return saldo;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((idConta == null) ? 0 : idConta.hashCode());
		result = prime * result
				+ ((operacoes == null) ? 0 : operacoes.hashCode());
		result = prime * result + ((titular == null) ? 0 : titular.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ContaAbstrata other = (ContaAbstrata) obj;
		if (idConta == null) {
			if (other.idConta != null)
				return false;
		} else if (!idConta.equals(other.idConta))
			return false;
		if (operacoes == null) {
			if (other.operacoes != null)
				return false;
		} else if (!operacoes.equals(other.operacoes))
			return false;
		if (titular == null) {
			if (other.titular != null)
				return false;
		} else if (!titular.equals(other.titular))
			return false;
		return true;
	}

}
